package cn.tedu.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class WebFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Object user = request.getSession().getAttribute("user");
        String servletPath = request.getServletPath();
//        System.out.println(servletPath);


        if(checkPath(servletPath)){
            filterChain.doFilter(request,response);
            return;
        }else if(user!=null){
            filterChain.doFilter(request,response);
            return;
        }
        response.sendRedirect("http://localhost:8080/html/login.html");
    }

    private boolean checkPath(String path){
        boolean flag=false;
        String[] paths={
                "/login",
                "/register",
                "/html/login.html",
                "/html/register.html",
                "/static/components/login.vue",

                "/static/components/register.vue",
                "/static/js/vue.js",

                "/static/components/register.vue"
        };
        for (String s : paths) {
            if(path.equals(s)){
                flag=true;
            }
        }

        return flag;
    }

    @Override
    public void destroy() {

    }
}
